package com.aischool.service;

import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

public class SysMenuService {

	public final String CK_CacheName = "CacheMenu";
	public final String CK_Sys_Menu_AppId_Pre = "CK_Sys_Menu_AppId_";
	
	public String getCacheKey(int app_id, int menu_state) {
		return "CK_Sys_Menu_AppId_" + app_id + "MenuState_" + menu_state;
	}
	
	@Inject
	SysPermissionService sysPermissionService;
	
	/**
	 * 获取应用菜单
	 * @return
	 */
	public List<Record> getAppMenu(int app_id, int menu_state){
		
		return Db.findByCache(CK_CacheName, getCacheKey(app_id, menu_state), 
				"SELECT a.*, b.app_name FROM sys_menu a INNER JOIN sys_app b ON b.app_id = a.app_id WHERE a.app_id = ? AND a.menu_state = ? ORDER BY a.parent_id, a.menu_sort, a.menu_id", 
				app_id, menu_state);
	}

	
	public Record getMenu(int menu_id) {
		return Db.findFirst("SELECT a.* FROM sys_menu a WHERE a.menu_id = ?", menu_id);
	}
	
	public boolean updateMenuState(int menu_id, int menu_state) {
		int ir = Db.update("UPDATE sys_menu SET menu_state = ? WHERE menu_id = ?", menu_state, menu_id);
		if (ir > 0) {
			removeCache();
		}
		return ir>0;
	}
	
	public void removeCache() {
		CacheKit.removeAll(CK_CacheName);
		sysPermissionService.removeCache();
	}
}
